package com.tcd.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tcd.helper.redis.RedisHelper;
import com.tcd.helper.redis.ZSetRedisHelper;
import com.tcd.mapper.PermissionMapper;
import com.tcd.pojo.Permission;
import com.tcd.service.PermissionService;
import com.tcd.utils.AccountUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author space
 * @since 2021-05-21
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Autowired(required = false)
    PermissionMapper permissionMapper;

    private static final String REDIS_VAL_NAME = "permissionSet";
    private static final String REDIS_VAL_KEY = "permissionId";

    @Override
    public List<Permission> getUserPermission(Integer uid) {
        List<Permission> list = permissionMapper.selectUserPermission(uid);
        return createPermissionTree(list);
    }

    @Override
    public List<Permission> getPermissionFilter(Integer pageIndex, Integer pageSize, String name, Integer[] levels, Integer parentId) {
        if (!RedisHelper.hasKey(REDIS_VAL_NAME)) {
            List<Permission> list = permissionMapper.selectPermissionFilter(1, 0, null, null, null);
            ZSetRedisHelper.addSet(REDIS_VAL_NAME, REDIS_VAL_KEY, list, true);
        }
        if (AccountUtils.isNull(name) && AccountUtils.isAllNull(levels, parentId)) {
            return ZSetRedisHelper.getValSet(REDIS_VAL_NAME, Permission.class, (pageIndex - 1) * pageSize, pageSize);
        } else {
            return permissionMapper.selectPermissionFilter(pageIndex, pageSize, name, levels, parentId);
        }
    }

    @Override
    public Integer getPermissionFilterCount(String name, Integer level, Integer parentId) {
        if (AccountUtils.isNull(name) && AccountUtils.isAllNull(level, parentId)) {
            return ZSetRedisHelper.getValCountSet(REDIS_VAL_NAME);
        }
        return permissionMapper.selectPermissionFilterCount(name, level, parentId);
    }

    @Override
    public List<Permission> getPermissionTree(Integer[] levels) {
        List<Permission> list = null;
        if (levels == null && RedisHelper.hasKey(REDIS_VAL_NAME)) {
            list = ZSetRedisHelper.getValSet(REDIS_VAL_NAME, Permission.class, 0, 0);
        } else {
            list = permissionMapper.selectPermissionFilter(0, -1, null, levels, null);
        }
        return createPermissionTree(list);
    }

    @Override
    public Integer addPermission(Permission permission) {
        int row = permissionMapper.insert(permission); //mybatis-plus添加
        if (row > 0) {
            ZSetRedisHelper.addSet(REDIS_VAL_NAME, REDIS_VAL_KEY, permission);
        }
        return row;
    }

    @Override
    public Integer updatePermission(Permission permission) {
        int row = permissionMapper.updateById(permission); //mybatis-plus修改
        if (row > 0) {
            ZSetRedisHelper.updateSet(REDIS_VAL_NAME, REDIS_VAL_KEY, permission);
        }
        return row;
    }

    @Override
    public Integer delPermissions(Integer[] ids) {
        if (ids == null || ids.length == 0)
            return 0;
        int row = permissionMapper.deleteBatchIds(Arrays.asList(ids)); //mybatis-plus删除
        if (row > 0) {
            ZSetRedisHelper.deleteSet(REDIS_VAL_NAME, ids);
        }
        return row;
    }

    @Override
    public List<Permission> getUserPermissionNoTree(int uid) {
        return permissionMapper.selectUserPermission(uid);
    }

    public List<Permission> createPermissionTree(List<Permission> permissions) {
        List<Permission> list = new ArrayList<>();
        for (int i = 0; i < permissions.size(); i++) {
            if (permissions.get(i).getParentId() == 0) {
                list.add(permissions.remove(i));
                i--;
            }
        }
        for (Permission permission : list) {
            setChildren2(permission, permissions);
        }
        return list;
    }

    public void setChildren(Permission parent, List<Permission> list) {
        for (Permission permission : list) {
            if (parent.getPermissionId() == permission.getParentId()) {
                if (permission.getPermissionLevel() != 3) {
                    setChildren(permission, list);
                }
                parent.getChildren().add(permission);
                list.remove(permission);
            }
        }
    }

    public Integer setChildren2(Permission parent, List<Permission> list) {
        Integer index = 0;  //记录当前遍历索引
        Integer count = 0;  //记录从list中移除元素的个数
        while (list.size() > 0 && index < list.size()) { //开始遍历遍历条件：list元素个数大于0   index小于list大小
            Permission permission = list.get(index);    //获取当前索引元素
            if (parent.getPermissionId() == permission.getParentId()) {  //如果父权限的id等于当前元素的id
                list.remove(permission);    //将当前权限从集合中移除
                if (permission.getPermissionLevel() != 3) {  //如果权限等级不等于3(非按钮权限)
                    //进行递归设置子节点，返回值为此次递归删除元素的次数,感觉删除元素的次数向后移
                    index -= setChildren2(permission, list);
                    index = index < 0 ? 0 : index;
                }
                //删除次数+1，当前索引-1
                count++;
                index--;
                //添加到父权限集合中
                parent.getChildren().add(permission);
            }
            index++;
        }
        return count;
    }

}
